package com.chengxiaoxiao.utils.db;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * 封装List集合
 */
public class BeanListHandler implements ResultSetHandler {

    private Class clazz;

    public BeanListHandler(Class clazz) {
        this.clazz = clazz;
    }


    @Override
    public Object handle(ResultSet rs) {

        try {
            List list = new ArrayList();
            while (rs.next()) {
                Object bean = clazz.newInstance();
                ResultSetMetaData rsmd = rs.getMetaData();
                int num = rsmd.getColumnCount();
                for (int i = 0; i < num; i++) {
                    String fieldName = rsmd.getColumnName(i + 1);
                     Object fieldValue = rs.getObject(i + 1);

                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    field.set(bean, fieldValue);
                }
                list.add(bean);
            }

            return list;


        } catch (Exception e) {

            throw new RuntimeException("封装数据失败");
        }

    }
}
